<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserRequest;
use App\User;
use File;
use Illuminate\Http\Request;
use function Sodium\compare;
use Storage;

class UsersController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth',['except'=>['show']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        return view('users.show',compact('user'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user)
    {
        $this->authorize('update',$user);
        return view('users.edit',compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UserRequest $request, User $user)
    {
        $data = $request->only(['name','introduction']);
        if ($request->file('avatar')) {
            $path = Storage::putFile('public/avatars/'.date('Y').'/'.date('m').'/'.date('d'),$request->file('avatar'));
            if ($path) {
                $data['avatar'] = $path;
            }
        }
        $user->update($data);

        return redirect()->route('users.show',$user->id)->with('success','个人资料更新成功!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
